package com.example.basecore.event;

import com.example.basecore.factory.EventHandlerFactory;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * @author ycd0075
 * @date 2024-01-25 23:04
 */
public class DefaultEventBus implements EventBus {
    private EventHandlerFactory eventHandlerFactory;

    public DefaultEventBus(EventHandlerFactory eventHandlerFactory) {
        this.eventHandlerFactory = eventHandlerFactory;
    }

    @Override
    public void fire(Event event) {
        Set<EventHandler> eventHandlerList = eventHandlerFactory.create(event);
        if(CollectionUtils.isEmpty(eventHandlerList)){
            return;
        }
        eventHandlerList.forEach(e -> e.handle(event));
    }

    @Override
    public void asyncFire(Event event) {
        Set<EventHandler> eventHandlerList = eventHandlerFactory.create(event);
        eventHandlerList.parallelStream().forEach(e -> e.handle(event));
    }
}
